package com.guli.edu.controller.admin;

import com.guli.common.constants.ResultCodeEnum;
import com.guli.common.exception.RRException;
import com.guli.common.vo.R;
import com.guli.edu.entity.Subject;
import com.guli.edu.service.SubjectService;
import com.guli.edu.vo.SubjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/admin/edu/subject")
public class SubjectAdminController {

	@Autowired
	private SubjectService subjectService;


	@PostMapping("/import")
	public R batchImport(@RequestParam("file") MultipartFile file) {

		try{
			List<String> errorMsg = subjectService.batchImport(file);
			if(errorMsg.size() == 0){
				return R.ok().message("批量导入成功");
			}else{
				return R.error().message("部分数据导入失败").data("errorMsgList", errorMsg);
			}

		}catch (Exception e){
			//无论哪种异常，只要是在excel导入时发生的，一律用转成RRException抛出
			throw new RRException(ResultCodeEnum.EXCEL_DATA_IMPORT_ERROR);
		}
	}

	@GetMapping("/list")
	public R subjectList(){
		List<SubjectNode> subjectList = subjectService.subjectList();
//		List<SubjectNode> subjectList2 = subjectService.subjectList2();
		return R.ok().data("items", subjectList);
	}

	/**
	 * 删除一级分类
	 */
	@DeleteMapping("{id}")
	public R deleteSubjectById(@PathVariable String id) {
		Boolean flag = subjectService.deleteSubjectById(id);
		if (flag) {
			return R.ok();
		}else {
			return R.error().message("删除失败");
		}
	}

	/**
	 * 新增分类
	 */
	@PostMapping("save-level")
	public R saveLevelOne(@RequestBody Subject subject){

		boolean result = subjectService.saveLevel(subject);
		if(result){
			return R.ok();
		}else{
			return R.error().message("新增分类失败");
		}
	}

}